@file:Suppress("unused")

package com.hjh.tool.extension

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import androidx.core.graphics.createBitmap
import com.elvishew.xlog.XLog
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import kotlin.apply
import kotlin.let
import kotlin.text.split

/**
 * @author hjh
 * @version 1.0
 * @since 1.0
 * @date 2024/4/4
 * @qq 3472903821
 * @description String类扩展方法
 */

fun String.isFileExist(): Boolean {
    val file = File(this)
    return if (file.exists()) true
    else file.mkdirs()
}

private val dateFormat = object : ThreadLocal<SimpleDateFormat>() {
    override fun initialValue(): SimpleDateFormat {
        return SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).apply {
            timeZone = TimeZone.getTimeZone("GMT+08:00")
        }
    }
}

fun String?.toDate(): Date? {
    return try {
        this?.let { dateFormat.get()?.parse(it) }
    } catch (e: Exception) {
        null
    }
}

private val dateFormat1 = object : ThreadLocal<SimpleDateFormat>() {
    override fun initialValue(): SimpleDateFormat {
        return SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).apply {
            timeZone = TimeZone.getTimeZone("GMT+08:00")
        }
    }
}

fun String?.toDayDate(): Date? {
    return try {
        this?.let { dateFormat1.get()?.parse(it.split(" ")[0]) }
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

fun String.toBitmap(): Bitmap? {
    runCatching {
        val decodedBytes: ByteArray = Base64.decode(this, Base64.DEFAULT)
        return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
    }.onFailure {
        return null
    }
    return null
}

fun String?.generateBarcode(width: Int, height: Int): Bitmap? {
    if (this == null) return null
    try {
        // 使用正确的提示类型，这里设置字符编码为 UTF-8
        val hints = mutableMapOf<EncodeHintType, Any>()
        hints[EncodeHintType.CHARACTER_SET] = "UTF-8"

        val multiFormatWriter = MultiFormatWriter()
        val bitMatrix =
            multiFormatWriter.encode(this, BarcodeFormat.CODE_128, width, height, hints)

        val pixels = IntArray(width * height)
        for (y in 0 until height) {
            for (x in 0 until width) {
                pixels[y * width + x] = if (bitMatrix.get(x, y)) {
                    0xFFFFFFFF.toInt()  // 白色
                } else {
                    0xFF000000.toInt()  // 黑色
                }
            }
        }

        return createBitmap(width, height).apply {
            setPixels(pixels, 0, width, 0, 0, width, height)
        }
    } catch (e: Exception) {
        e.printStackTrace()
        XLog.e("$this 条形码生成失败: ${e.message}")
        return null
    }
}